<?php

namespace app\api\controller\xiservice;


use addons\xiservice\controller\WeixinMini;
use app\common\controller\xiservice\XiserviceApi;
use app\common\model\xiservice\User as XiserviceUser;
use app\common\model\xiservice\VipConfig;
use app\common\model\xiservice\VipOrder;
use fast\Http;

/**
 * 包年包月接口
 */
class Vip extends XiserviceApi
{

    protected $noNeedLogin = ['lists', 'analog_notify'];
    protected $noNeedRight = ['*'];

    protected $model = null;

    /**
     * 包年包月列表
     */
    public function lists()
    {
        $lists = VipConfig::field('id,name,price,describe')
            ->where(function ($query) {

            })
            ->paginate();
        $this->success('ok', $lists);
    }

    /**
     * 创建vip包年包月订单
     */
    public function createviporder()
    {
        $id = $this->request->param('vip_id/d');

        $vipConfig = VipConfig::where('id', $id)->find();
        if(!$vipConfig) {
            $this->error('包年包月配置不存在');
        }

        $user = XiserviceUser::where('user_id', $this->auth->id)->find();
        //判断原来的包年月是否存在
        if($user['vip_end_time'] > time()) {
            //存在包年月
            if($user['vip_type'] != $vipConfig['type']){
                $this->error('包年月服务中...');
            }
        }

        $price = $vipConfig['price'];
        $result['data'] = [
            'pay_money' => $price,
            'day' => $vipConfig['day'],
            'pay_status' => '10',
            'name' => $vipConfig['name'],
            'type' => $vipConfig['type'],
            'divide_rate' => $vipConfig['divide_rate'],
        ];
        $this->model = new VipOrder();
        $res = $this->model->createOrder($result['data'], $this->auth->id);
        if (!$res['status']) {
            $this->error($res['msg']);
        }
        $orderInfo = $this->model->where('id', $res['data'])->find();

        //创建微信订单 进行支付

        $num = mt_rand(10, 99);
        $order_no = $orderInfo['order_no'] . '_' . $num;

        $orderpay = array(
            'trade_type' => 'JSAPI',// 请对应换成你的支付方式对应的值类型
            'out_trade_no' => $order_no,//订单号
            'body' => $orderInfo['name'],//
            'total_fee' => $price,//支付金额，这边传单位为元的就可以。
            'openid' => $user['mini_openid'],//用户openID
        );

        $wx = new WeixinMini();
        $ret = $wx->union_order($orderpay);
        if ($ret['status']) {
            //todo 生产环境请屏蔽
            Http::sendAsyncRequest(request()->domain().'/index.php/api/xiservice.vip/analog_notify', ['id' => $orderInfo->id]);

            $this->success('创建微信订单成功', ['wxconfig' => $ret['wxconfig'], 'chose_type' => $orderInfo['type'], 'pay_money' => $orderInfo['pay_money'], 'order_no' => $orderInfo['order_no'], 'id' => $orderInfo['id']]);
        } else {
            $this->error("创建微信订单失败", ['wxconfig' => [], 'chose_type' => $orderInfo['type'], 'pay_money' => $orderInfo['pay_money'], 'order_no' => $orderInfo['order_no'], 'id' => $orderInfo['id']]);
        }
    }

    /**
     * todo 生成环境必须屏蔽
     * 模拟回调
     */
    public function analog_notify()
    {
        $oid = $this->request->param('id');
        $order = VipOrder::get($oid);
        $user = XiserviceUser::where('user_id', $order->user_id)->find();
        $config = \addons\xiservice\library\Config::load();
        $xmlArr = [
            'return_code' => 'SUCCESS',
            'result_code' => 'SUCCESS',
            'appid' => $config['app_id'],
            'mch_id' => $config['mch_id'],
            'nonce_str' => mt_rand(10000000, 99999999),
            'sign_type' => 'MD5',
            'openid' => $user['mini_openid'],
            'is_subscribe' => 'N',
            'trade_type' => 'JSAPI',
            'bank_type' => 'CFT',
            'total_fee' => $order->pay_money * 100,
            'cash_fee' => $order->pay_money * 100,
            'transaction_id' => str_replace('VP', '1234', $order->order_no),
            'out_trade_no' => $order->order_no . '_' . mt_rand(100, 999),
            'time_end' => date('YmdHis'),
        ];
        ksort($xmlArr);
        $string = '';
        foreach ($xmlArr as $k => $v) {
            $string .= $k . '=' . $v . '&';
        }
        $string .= 'key=' . $config['key'];
        $xmlArr['sign'] = strtoupper(md5($string));

        $xml = '<xml>';
        foreach ($xmlArr as $k => $v) {
            $xml .= '<' . $k . '>' . $v . '</' . $k . '>';
        }
        $xml .= '</xml>';

        $res = Http::post($config['notify_url'], $xml, [
            CURLOPT_HTTPHEADER => [
                'content-type: application/xml'
            ]
        ]);
        dump($res);
    }

}
